<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;

class Review extends BaseController
{
    /**
     * 获取联系人审核列表
     */
    public function contactList()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $status = $params['status'] ?? 1; // 默认显示待审核
        
        $query = Db::name('crm_contact_review')
            ->alias('r')
            ->field('r.*, c.name as contact_name, cu.name as customer_name, u.name as user_name')
            ->leftJoin('crm_contact c', 'r.contact_id = c.id')
            ->leftJoin('crm_customer cu', 'r.customer_id = cu.id')
            ->leftJoin('admin u', 'r.user_id = u.id')
            ->where('r.status', $status);
            
        $total = $query->count();
        $list = $query->order('r.create_time', 'desc')
            ->page($page, $limit)
            ->select();
        
        // 处理列表数据
        $list = $list ? $list->toArray() : [];
        foreach ($list as &$item) {
            // 如果字段为空，从new_data中解析
            if (!empty($item['new_data'])) {
                $newData = json_decode($item['new_data'], true);
                if (empty($item['contact_name'])) {
                    $item['contact_name'] = $newData['name'] ?? '';
                }
            }
            
            // 格式化时间
            $item['create_time'] = $this->formatTime($item['create_time']);
            $item['update_time'] = $this->formatTime($item['update_time']);
        }
            
        return $this->paginate($list, $total, (int)$page, (int)$limit);
    }
    
    /**
     * 审核联系人修改/删除申请
     */
    public function contactReview()
    {
        $params = Request::param();
        $id = $params['id'];
        $status = $params['status']; // 2: 通过, 3: 驳回
        $reviewComment = $params['review_comment'] ?? '';
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        // 获取用户信息判断是否为管理员
        $userInfo = Db::name('admin')
            ->field('id, group_id, did')
            ->where('id', $userId)
            ->find();
        
        // 只有管理员可以审核
        if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] != 1)) {
            return $this->error('无权限审核');
        }
        
        $review = Db::name('crm_contact_review')->where('id', $id)->find();
        if (!$review) {
            return $this->error('审核记录不存在');
        }
        
        if ($review['status'] != 1) {
            return $this->error('该申请已审核完成');
        }
        
        // 更新审核记录
        $reviewData = [
            'status' => $status,
            'reviewer_id' => $userId,
            'review_comment' => $reviewComment,
            'review_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        Db::name('crm_contact_review')->where('id', $id)->update($reviewData);
        
        // 如果审核通过，执行相应的操作
        if ($status == 2) {
            $this->executeContactReview($review);
        }
        
        return $this->success($review, '获取成功');
    }
    
    /**
     * 执行联系人审核通过的操作
     */
    private function executeContactReview($review)
    {
        $originalData = json_decode($review['original_data'], true);
        $newData = json_decode($review['new_data'], true);
        
        switch ($review['review_type']) {
            case 2: // 编辑
                $updateData = [
                    'name' => $newData['name'] ?? $originalData['name'],
                    'position' => $newData['position'] ?? $originalData['position'],
                    'phone' => $newData['phone'] ?? $originalData['phone'],
                    'wechat' => $newData['wechat'] ?? $originalData['wechat'],
                    'email' => $newData['email'] ?? $originalData['email'],
                    'is_primary' => $newData['is_primary'] ?? $originalData['is_primary'],
                    'update_time' => date('Y-m-d H:i:s')
                ];
                
                // 如果设置为主要联系人，取消其他主要联系人
                if ($updateData['is_primary'] == 1) {
                    Db::name('crm_contact')
                        ->where('customer_id', $review['customer_id'])
                        ->where('id', '<>', $review['contact_id'])
                        ->where('is_primary', 1)
                        ->update(['is_primary' => 0]);
                }
                
                Db::name('crm_contact')
                    ->where('id', $review['contact_id'])
                    ->update($updateData);
                break;
                
            case 3: // 删除
                Db::name('crm_contact')
                    ->where('id', $review['contact_id'])
                    ->update(['delete_time' => date('Y-m-d H:i:s')]);
                break;
        }
    }
    
    /**
     * 获取审核状态选项
     */
    public function statusOptions()
    {
        $options = [
            ['value' => 1, 'label' => '待审核'],
            ['value' => 2, 'label' => '审核通过'],
            ['value' => 3, 'label' => '审核驳回']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取审核类型选项
     */
    public function typeOptions()
    {
        $options = [
            ['value' => 2, 'label' => '编辑'],
            ['value' => 3, 'label' => '删除']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 格式化时间
     */
    private function formatTime($time)
    {
        if (empty($time)) {
            return '';
        }
        
        // 如枟是时间戳
        if (is_numeric($time)) {
            return date('Y-m-d H:i:s', $time);
        }
        
        // 如枟是日期时间字符串
        if (is_string($time)) {
            $timestamp = strtotime($time);
            if ($timestamp !== false) {
                return date('Y-m-d H:i:s', $timestamp);
            }
        }
        
        return $time;
    }
}